package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.GgCatalog;
import cn.com.yx.ms.domain.dbmodel.GgDevggMap;
import cn.com.yx.ms.domain.dbmodel.GgMain;
import cn.com.yx.ms.domain.gg.GgMainModel;
import cn.com.yx.ms.domain.mq.MqPushNoticeModel;
import cn.com.yx.ms.domain.mq.MqSelectedDevModel;
import cn.com.yx.ms.domain.mq.MqSelectedNoticeModel;
import cn.com.yx.ms.domain.program.CatalogModel;
import cn.com.yx.ms.persistence.GgCatalogMapper;
import cn.com.yx.ms.persistence.GgDevggMapMapper;
import cn.com.yx.ms.persistence.GgMainMapper;
import cn.com.yx.ms.persistence.JmProgramFileMapMapper;
import cn.com.yx.ms.service.IGgService;
import cn.com.yx.ms.service.ILogService;
import cn.com.yx.ms.service.IUserContextService;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.util.DateUtil;
import cn.yx.framework.view.ApiResult;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class GgServiceImpl implements IGgService {

    @Resource
    private ILogService iLogService;
    @Resource
    private IUserContextService iUserContextService;
    @Resource
    private GgCatalogMapper ggCatalogMapper;
    @Resource
    private GgMainMapper ggMainMapper;
    @Resource
    private GgDevggMapMapper ggDevggMapMapper;
    @Resource
    private JmProgramFileMapMapper jmProgramFileMapMapper;

    // region << 公告目录 >>
    @Override
    public ApiResult saveGgCatalog(CatalogModel catalogModel) {
        ApiResult result = null;


        if (!StringUtils.isNoneBlank(catalogModel.getName())) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "目录名称不能为空");
        }


        //判断同级下目录名称是否重复
        int countByName = ggCatalogMapper.selectCountByGgCatalogName(catalogModel.getParentid(), catalogModel.getName());
        if (!StringUtils.isNoneBlank(catalogModel.getId()) && countByName > 0) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "同级目录下目录名不能重复，请重新输入");
        }

        GgCatalog ggCatalog = ggCatalogMapper.selectByPrimaryKey(catalogModel.getId());

        if (ggCatalog == null) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", insertGgCatalog(catalogModel));

        } else {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", updateGgCatalog(catalogModel));

        }

        return result;
    }

    @Override
    public int insertGgCatalog(CatalogModel catalogModel) {
        GgCatalog ggCatalog = new GgCatalog();

        if (!StringUtils.isNoneBlank(catalogModel.getId())) {
            catalogModel.setId(UUID.randomUUID().toString());
        }

        ggCatalog.setGuid(catalogModel.getId());
        ggCatalog.setName(catalogModel.getName());
        ggCatalog.setParentid(catalogModel.getParentid());
        ggCatalog.setLevel(0);
        ggCatalog.setNumber(ggCatalogMapper.getMaxNumber(catalogModel.getParentid()));
        ggCatalog.setOrderindex(catalogModel.getOrderindex());
        ggCatalog.setCreatetime(new Date());
        ggCatalog.setUpdatetime(new Date());
        ggCatalog.setIsdeleted(0);
        int result = ggCatalogMapper.insert(ggCatalog);
        if (result > 0) {
            iLogService.log("info",
                    "公告目录管理",
                    "创建成功-【" + JSON.toJSONString(ggCatalog) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public ApiResult deleteGgCatalog(String id) {
        //int result = ggCatalogMapper.deleteByPrimaryKey(id);
        ApiResult result = null;
        int count = 0;

        GgCatalog ggCatalog = ggCatalogMapper.selectByPrimaryKey(id);
        if (ggCatalog != null) {

            //判断公告目录是否存在子节点
            List<GgCatalog> childs = ggCatalogMapper.selectChildByParentId(id);
            if (childs != null && childs.size() > 0) {
                return new ApiResult(AppConstant.MSG_FAILURE, false, "存在子目录，不允许删除");
            }

            ggCatalog.setIsdeleted(1);
            count = ggCatalogMapper.updateByPrimaryKey(ggCatalog);

            //删除目录下对应的公告内容
            ApiQueryBase query = new ApiQueryBase();
            query.setConditions(new HashMap<String, Object>());
            query.getConditions().put("catalogid", ggCatalog.getGuid());
            List<GgMain> ggMains = ggMainMapper.find(query);
            if (ggMains != null && ggMains.size() > 0) {
                for (int i = 0; i < ggMains.size(); i++) {
                    ggMains.get(i).setIsdeleted(1);
                    ggMainMapper.updateByPrimaryKey(ggMains.get(i));
                }
            }
            if (count > 0) {
                iLogService.log("info",
                        "公告目录管理",
                        "删除成功-【" + id + "】-【" + ggCatalog.getName() + "】",
                        iUserContextService.getUserContext().getId());
            }
        }


        result = new ApiResult(AppConstant.MSG_SUCCESS, true, "删除成功");
        return result;
    }

    @Override
    public int updateGgCatalog(CatalogModel catalogModel) {
        GgCatalog ggCatalog = ggCatalogMapper.selectByPrimaryKey(catalogModel.getId());
        ggCatalog.setName(catalogModel.getName());
        ggCatalog.setOrderindex(catalogModel.getOrderindex());
        ggCatalog.setUpdatetime(new Date());
        ggCatalog.setIsdeleted(0);
        int result = ggCatalogMapper.updateByPrimaryKey(ggCatalog);
        if (result > 0) {
            iLogService.log("info",
                    "公告目录管理",
                    "修改成功-【" + JSON.toJSONString(ggCatalog) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public List<CatalogModel> findGgCatalogs(ApiQueryBase apiQueryBase) {
        GgCatalog ggCatalog = ggCatalogMapper.selectByPrimaryKey("root");
        List<GgCatalog> ggCatalogs = ggCatalogMapper.find(apiQueryBase);
        List<CatalogModel> ggCatalogModels = new ArrayList<CatalogModel>();

        //初始化根节点
        CatalogModel root = new CatalogModel();
        root.setId(ggCatalog.getGuid());
        root.setName(ggCatalog.getName());
        root.setNumber(ggCatalog.getNumber());
        root.setChildren(new ArrayList<CatalogModel>());

        BuildGgCatalogTree(root, ggCatalogs);

        if (root.getChildren() != null && root.getChildren().size() != 0) {
            root.setIsleaf(0);
        } else {
            root.setIsleaf(1);
        }

        ggCatalogModels.add(root);
        return ggCatalogModels;
    }

    private void BuildGgCatalogTree(CatalogModel node, List<GgCatalog> ggCatalogs) {
        for (GgCatalog ggCatalog :
                ggCatalogs) {
            if (ggCatalog.getParentid() != null && ggCatalog.getParentid().equals(node.getId())) {
                CatalogModel child = new CatalogModel();
                child.setId(ggCatalog.getGuid());
                child.setName(ggCatalog.getName());
                child.setParentid(ggCatalog.getParentid());
                child.setNumber(ggCatalog.getNumber());
                child.setOrderindex(ggCatalog.getOrderindex());
                child.setChildren(new ArrayList<CatalogModel>());

                node.getChildren().add(child);

                //递归调用
                BuildGgCatalogTree(child, ggCatalogs);
                if (child.getChildren() != null && child.getChildren().size() != 0) {
                    child.setIsleaf(0);
                } else {
                    child.setIsleaf(1);
                }
            }
        }

    }


    @Override
    public CatalogModel findGgCatalog(String id) {
        CatalogModel catalogModel = null;
        GgCatalog ggCatalog = ggCatalogMapper.selectByPrimaryKey(id);
        if (ggCatalog != null) {
            catalogModel = new CatalogModel();
            catalogModel.setId(ggCatalog.getGuid());
            catalogModel.setParentid(ggCatalog.getParentid());
            catalogModel.setName(ggCatalog.getName());
            catalogModel.setOrderindex(ggCatalog.getOrderindex());
        }
        return catalogModel;
    }

    // endregion

    // region << 公告管理 >>
    @Override
    public ApiResult saveGgMain(GgMainModel ggMainModel) {
        ApiResult result = null;

        if (!StringUtils.isNoneBlank(ggMainModel.getTitle())) {
            result = new ApiResult(AppConstant.MSG_FAILURE, false, "请输入公告标题");
            return result;
        }

        if (!StringUtils.isNoneBlank(ggMainModel.getGuid())) {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", insertGgMain(ggMainModel));
        } else {
            result = new ApiResult().success(AppConstant.MSG_SUCCESS, "", updateGgMain(ggMainModel));
        }

        return result;
    }

    @Override
    public int insertGgMain(GgMainModel ggMainModel) {
        GgMain ggMain = new GgMain();

        if (!StringUtils.isNoneBlank(ggMainModel.getGuid())) {
            ggMainModel.setGuid(UUID.randomUUID().toString());
        }

        ggMain.setGuid(ggMainModel.getGuid());
        ggMain.setTitle(ggMainModel.getTitle());
        ggMain.setCatalogid(ggMainModel.getCatalogid());
        ggMain.setContent(ggMainModel.getContent());
        ggMain.setCreatetime(new Date());
        ggMain.setIsdeleted(0);
        ggMain.setOrderindex(0);
        //保存公告信息
        int result = ggMainMapper.insert(ggMain);
        if (result > 0) {
            iLogService.log("info",
                    "公告管理",
                    "创建成功-【" + JSON.toJSONString(ggMain) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public int deleteGgMain(String id) {
        int result = 0;
        GgMain ggMain = ggMainMapper.selectByPrimaryKey(id);
        if (ggMain != null) {
            ggMain.setIsdeleted(1);
            result = ggMainMapper.updateByPrimaryKey(ggMain);
            // result = ggMainMapper.deleteByPrimaryKey(id);
            jmProgramFileMapMapper.updateMapByResourceId(id);

            if (result > 0) {
                iLogService.log("info",
                        "公告管理",
                        "删除成功-【" + id + "】-【" + ggMain.getTitle() + "】",
                        iUserContextService.getUserContext().getId());
            }
        }
        return result;
    }

    @Override
    public int updateGgMain(GgMainModel ggMainModel) {
        GgMain ggMain = ggMainMapper.selectByPrimaryKey(ggMainModel.getGuid());
        ggMain.setTitle(ggMainModel.getTitle());
        ggMain.setContent(ggMainModel.getContent());
        int result = ggMainMapper.updateByPrimaryKey(ggMain);
        if (result > 0) {
            iLogService.log("info",
                    "公告管理",
                    "修改成功-【" + JSON.toJSONString(ggMain) + "】",
                    iUserContextService.getUserContext().getId());
        }
        return result;
    }

    @Override
    public List<GgMain> findGgMains(ApiQueryBase apiQueryBase) {
        return ggMainMapper.find(apiQueryBase);
    }

    @Override
    public List<GgMain> findGgByEquipmentNo(String equipmentNo){
        return ggMainMapper.findByEquipmentNo(equipmentNo);
    }

    @Override
    public GgMainModel findGgMain(String id) {
        GgMainModel ggMainModel = null;
        GgMain ggMain = ggMainMapper.selectByPrimaryKey(id);
        if (ggMain != null) {
            ggMainModel = new GgMainModel();
            ggMainModel.setGuid(ggMain.getGuid());
            ggMainModel.setTitle(ggMain.getTitle());
            ggMainModel.setCatalogid(ggMain.getCatalogid());
            ggMainModel.setContent(ggMain.getContent());
            ggMainModel.setCreatetime(DateUtil.date2String(ggMain.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));

        }
        return ggMainModel;
    }

    @Override
    public void saveDevGgMap(MqPushNoticeModel mqPushNoticeModel) {
        if (mqPushNoticeModel != null) {
            if (mqPushNoticeModel.getMqSelectedDevModels() != null) {
                for (MqSelectedDevModel dev : mqPushNoticeModel.getMqSelectedDevModels()) {
                    ggDevggMapMapper.deleteByDevsn(dev.getDevsn());
                    if (mqPushNoticeModel.getMqSelectedNoticeModels() != null) {
                        int orderindex = 0;
                        for (MqSelectedNoticeModel notice : mqPushNoticeModel.getMqSelectedNoticeModels()) {
                            GgDevggMap ggDevggMap = new GgDevggMap();
                            ggDevggMap.setGuid(UUID.randomUUID().toString());
                            ggDevggMap.setDevid(dev.getDevsn());
                            ggDevggMap.setGgid(notice.getId());
                            ggDevggMap.setCreatetime(new Date());
                            ggDevggMap.setOrderindex(orderindex++);
                            ggDevggMapMapper.insert(ggDevggMap);
                        }
                    }
                }
            }
        }
    }
    // endregion
}